package com.mobor.moborsvr.obj.category.dao.impl;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.mobor.moborsvr.obj.category.categories.CategoryObjectDO;
import com.mobor.moborsvr.obj.category.dao.CategoryObjectDao;

/**
 * Implementation of {@link CategoryObjectDao} interface.
 * @author teroleg
 *
 */
public class CategoryObjectDaoImpl implements CategoryObjectDao {
	
	private Long coId = null;
	
	private static final Logger logger = LogManager.getLogger(CategoryObjectDaoImpl.class.getName());
	
	private SessionFactory sessionFactory;
	
	private final static String GET_ALL_CATEGORIES = "from CategoryObjectDO";
	private final static String GET_CATEGORY_BY_ID = "from CategoryObjectDO co where co.id = ";
    
    /* (non-Javadoc)
	 * @see com.mobor.svr.obj.category.dao.CategoryObjectDao#getCategoryObjects()
	 */
    @Override
	@SuppressWarnings("unchecked")
	public List<CategoryObjectDO> getCategoryObjects() {
    	logger.debug("Searching for object categories.");
    	
    	Session session = sessionFactory.openSession();    	
    	Query q = session.createQuery(GET_ALL_CATEGORIES);
    	List<CategoryObjectDO> objList = q.list();
    	session.close();
    	
    	logger.debug("Searching for object categories finished.");
    	
    	return objList;    	
    }

	@Override
	public List<?> work() {
		if(coId != null)
			return getObjectCategory(this.coId);
		
		return getCategoryObjects();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CategoryObjectDO> getObjectCategory(Long coId) {
		logger.debug("Searching for object category with id: " + coId);
    	
    	Session session = sessionFactory.openSession();    	
    	Query q = session.createQuery(GET_CATEGORY_BY_ID + coId);
    	List<CategoryObjectDO> objList = q.list();
    	session.close();
    	
    	logger.debug("Searching for object categories finished.");
    	
    	return objList;
	}	
	
	public Long getCoId() {
		return coId;
	}

	public void setCoId(Long coId) {
		this.coId = coId;
	}

	public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }
}
